<?php
class PostModel extends Model {
    protected $fields=array(
    'id','category','model','title','created','modified','userid','auditid','author','source','keywords','summary','thumb','jump','status',
    'viewpermit','comment','commentnum','content',
    '_pk'=>'id',
    '_autoInc'=>true
    );

    protected $_auto=array(
    array('title','trim','ALL','function'),
    );

    protected $_validate=array(
    array('title','require','标题不能为空')
    );

    protected $postMetaConfigs;

    public function _initialize() {
        parent::_initialize();
        $this->postMetaConfigs=include CONFIG_PATH.'PostMeta.php';
    }

    /**
     * 保存文档
     */
    public function savePost() {
        $baseVo=$this->create();
        if(!$baseVo) {
            return false;
        }
        $postMetaDao=new PostMetaModel();
        $baseVo=array_merge($baseVo,$postMetaDao->beforeSave($baseVo));
        //创建时间等
        $baseVo['created']=date('Y-m-d H:i:s');
        $baseVo['userid']=$_SESSION[C('USER_AUTH_KEY')]['id'];
        $this->startTrans();
        if($this->add($baseVo)) {
            $baseVo['id']=$this->getLastInsID();
            $postMetaDao->afterSave($baseVo);
            if($this->commit()) {
                return $baseVo;
            }
        }
        $this->rollback();
        $this->error=SAVE_FAIL;
        return false;
    }

    /**
     * 更新文档
     * @Event:UpdatePost (TODO)
     */
    public function updatePost(){
        $baseVo=$this->create();
        if(!$baseVo) {
            return false;
        }
        //TODO 未检查是否有权限修改此篇POST
        $postModel=$_POST['postModel'];
        $model=null;
        //元数据处理
        $postMetaDao=new PostMetaModel();
        $baseVo=array_merge($baseVo, $postMetaDao->beforeSave($baseVo));
        //更新时间
        $baseVo['modified']=date('Y-m-d H:i:s');
        $this->startTrans();
        if($this->save($baseVo,'id='.$baseVo['id'])){
            $postMetaDao->afterSave($baseVo);
            if($this->commit()) {
                return true;
            }
        }
        $this->rollback();
        $this->error=UPDATE_FAIL;
        return false;
     }

}
